
#define LONG_MAX 0x7fffffff
#define LONG_MIN 0xffffffff

int tolower(int c)
{
	if(c >= 'A' && c <= 'Z')
		return c - 'A';
	else return c;
}

int isspace(int c)
{
	if( c == ' ' || c == '\t' || c == '\n' || c == '\v' || c=='\f' || c=='\r' )
		return true;
	else return false;
}

//string to something calls
long int strtol(const char* str, char** endptr, int base)
{
	long int r = 0;
	const char* p = str;

	//eat whitespace
	while(*p && isspace(*p))
		++p;

	//look for sign
	int sign = 1;
	switch(*p)
	{
	case '-':
		sign = -1;
	case '+':
		++p;
	}

	//look for base
	if(*p && base == 0)
	{
		if(*p == '0')
			if(*(p+1) == 'x' || *(p+1) == 'X')
				base = 16;
			else
				base = 8;
		else
			base = 10;
	}

	//translate
	bool done = false;
	while(*p && !done)
	{
		//translate the character to a base value
		int v = 33;
		if(*p >= '0' && *p <= '9')
			v = int(*p - '0');
		else if( tolower(*p) >= 'a' && tolower(*p) <= 'z') //
			v = int(*p - 'a');

		//exclude anything out-of-base
		if(v > base)
			done = true;
		else
		{
			//
			r = r*base;

			//detect overflow
			if(r + v < r)
			{
				r = sign ? LONG_MAX : LONG_MIN;
				done = true;
			}
			else 
			{
				r += v;
			}
		}			
	}

	if(endptr)
		*endptr = const_cast<char*>(p);

	return r;
}